import { request } from '@umijs/max';
import { message } from 'antd';
import type { ApiType, ApiInfo, TablePagination } from './types';

const getErrorMessage = (error: any) => {
  const errorString = JSON.stringify(error);
  if (errorString.includes('ECONNABORTED')) {
    return '远程主机拒绝网络连接，请检查数据源或服务器配置！';
  }
  return '出错啦，message:' + error.message + '，code:' + error.code + '。';
};

/** 数据源
 * @param type
 * @param apiInfo
 * @param successMessage 成功消息提示 空字符串不提示 undefined默认提示
 * @returns
 */
export const dataSource = async (type: ApiType, apiInfo: ApiInfo, successMessage?: string): Promise<any> => {
  const { url, method, afterScript, parameter, body } = apiInfo;
  if (!url) {
    message.error('url不能为空，请配置数据源。');
    return Promise.resolve(undefined);
  }
  if (!method) {
    message.error('method不能为空。');
    return Promise.resolve(undefined);
  }

  let response = {};
  await request(url, {
    method,
    params: parameter,
    data: body,
    headers: {
      'Content-Type': 'application/json',
    },
  })
    .then(
      (res) => {
        if (successMessage === '') {
        } else if (!successMessage) {
          message.success('数据源请求成功。');
        } else {
          message.success(successMessage);
        }
        response = res;
      },
      (err) => {
        message.error(getErrorMessage(err));
      },
    )
    .catch(function (error) {
      message.error('出错了', error);
    });

  let returnData: any = {};
  let dataList: any;
  let total: any;
  // console.debug('执行脚本前数据', response, afterScript);
  try {
    // eslint-disable-next-line no-eval
    eval(afterScript);
  } catch (err) {
    message.error('后执行脚本出错。' + err);
    console.error('后执行脚本出错。', err);
  }
  console.debug('执行脚本后数据', 'returnData:', returnData, 'dataList:', dataList, 'total:', total);
  switch (type) {
    case 'list': {
      // returnData.forEach((item: any, index: number) => {
      //   // 初始化没有唯一键，手动赋值唯一id
      //   item['table-hide-id'] = index;
      // });
      if (dataList && total) {
        const tablePagination: TablePagination = {
          dataList: dataList,
          total: total,
        };
        return tablePagination;
      } else {
        const tablePagination: TablePagination = {
          dataList: [],
          total: 0,
        };
        return tablePagination;
      }
    }
    case 'detail': {
      if (returnData) {
        return returnData;
      } else {
        return {};
      }
    }
  }
};
